<template>
  <div id="app" :class="{ 'hide-nav': !showNav }">
    <!-- 顶部导航栏 -->
    <NavBar v-if="showNav" />
    
    <!-- 主内容区 -->
    <main class="main-content">
      <router-view v-slot="{ Component }">
        <transition 
          :name="transitionName" 
          mode="out-in"
          @before-leave="beforeLeave"
          @enter="enter"
          @after-enter="afterEnter"
        >
          <component :is="Component" />
        </transition>
      </router-view>
    </main>

    <!-- 全局加载状态 -->
    <GlobalLoading v-if="loading" />

    <!-- 返回顶部按钮 -->
    <el-backtop 
      :right="20" 
      :bottom="20"
      :visibility-height="400"
    >
      <el-icon><ArrowUp /></el-icon>
    </el-backtop>

    <!-- 全局消息提示 -->
    <el-config-provider :locale="zhCn">
      <router-view name="message" />
    </el-config-provider>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import { ArrowUp } from '@element-plus/icons-vue'
import NavBar from './components/NavBar.vue'
import GlobalLoading from './components/GlobalLoading.vue'
import { useAuthStore } from './stores/authStore'
import { useHeritageStore } from './stores/heritageStore'

// Patch ResizeObserver to suppress the warning in development
// This is a common workaround for 'ResizeObserver loop completed with undelivered notifications'
if (process.env.NODE_ENV === 'development') {
  const debounce = (callback, delay) => {
    let tid;
    return function(...args) {
      const ctx = this;
      tid && clearTimeout(tid);
      tid = setTimeout(() => {
        callback.apply(ctx, args);
      }, delay);
    };
  };

  const originalResizeObserver = window.ResizeObserver;
  window.ResizeObserver = class ResizeObserver extends originalResizeObserver {
    constructor(callback) {
      super(debounce(callback, 16)); // Debounce the callback with a 16ms delay
    }
  };
}

// 路由相关
const route = useRoute()
const router = useRouter()
const showNav = ref(true)
const transitionName = ref('fade')

// 状态管理
const authStore = useAuthStore()
const heritageStore = useHeritageStore()
const loading = ref(false)

// 监听路由变化
watch(() => route.path, (newPath) => {
  // 登录页和注册页隐藏导航栏
  showNav.value = !['/login', '/register'].includes(newPath)
  
  // 设置过渡动画
  transitionName.value = newPath.includes('/heritage/detail') ? 'slide' : 'fade'
  
  // 更新页面标题
  document.title = getPageTitle(newPath)
  
  // 滚动到顶部
  window.scrollTo(0, 0)
})

// 获取页面标题
const getPageTitle = (path) => {
  const titleMap = {
    '/': '首页 - 非遗传承',
    '/login': '登录 - 非遗传承',
    '/register': '注册 - 非遗传承',
    '/profile': '个人中心 - 非遗传承',
    '/heritage/list': '非遗项目 - 非遗传承',
    '/heritage/map': '地区分布 - 非遗传承',
    '/heritage/search': '搜索 - 非遗传承',
    '/masters': '传承人 - 非遗传承',
    '/stories': '传承故事 - 非遗传承',
    '/events': '活动资讯 - 非遗传承'
  }
  return titleMap[path] || '非遗传承'
}

// 过渡动画钩子
const beforeLeave = (el) => {
  // 保存滚动位置
  el._scrollTop = window.scrollY
}

const enter = (el) => {
  // 重置滚动位置
  window.scrollTo(0, 0)
}

const afterEnter = (el) => {
  // 恢复滚动位置
  if (el._scrollTop) {
    window.scrollTo(0, el._scrollTop)
    delete el._scrollTop
  }
}

// 全局错误处理
const handleError = (error) => {
  console.error('Global error:', error)
  ElMessage.error(error.message || '操作失败，请重试')
}

// 全局加载状态管理
const startLoading = () => {
  loading.value = true
}

const stopLoading = () => {
  loading.value = false
}

// 初始化数据
const initializeData = async () => {
  startLoading()
  try {
    // 获取非遗数据
    await heritageStore.fetchHeritageData()
    
    // 检查用户认证状态
    if (authStore.isAuthenticated) {
      // 可以在这里添加获取用户信息的逻辑
    }
  } catch (error) {
    handleError(error)
  } finally {
    stopLoading()
  }
}

// 生命周期钩子
onMounted(() => {
  // 初始化数据
  initializeData()
  
  // 添加全局错误处理
  window.addEventListener('error', handleError)
  window.addEventListener('unhandledrejection', handleError)
})

onUnmounted(() => {
  // 移除全局错误处理
  window.removeEventListener('error', handleError)
  window.removeEventListener('unhandledrejection', handleError)
})
</script>

<style>
html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
}

#app {
  font-family: 'Helvetica Neue', Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: transparent; /* Ensure app background is transparent to show body background */
  background-image: url('@/assets/main_background.jpg'); /* Set the background image */
  background-size: cover; /* Cover the entire element */
  background-position: center center; /* Center the image */
  background-repeat: no-repeat; /* Do not repeat the image */
  background-attachment: fixed; /* Keep background fixed when scrolling */
}

/* Main content area styling */
.main-content {
  flex: 1;
  padding: 20px;
  margin-top: 60px; /* Navigation bar height */
  background-color: rgba(255, 255, 255, 0.85); /* Semi-transparent white background for content to make it readable */
  border-radius: 8px; /* Slightly rounded corners for main content */
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05); /* Subtle shadow */
  transition: margin-top 0.3s ease;
  backdrop-filter: blur(2px); /* Apply a slight blur effect to the background behind content */
}

.hide-nav .main-content {
  margin-top: 0;
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.slide-enter-active,
.slide-leave-active {
  transition: transform 0.3s ease;
}

.slide-enter-from {
  transform: translateX(100%);
}

.slide-leave-to {
  transform: translateX(-100%);
}

/* 返回顶部按钮样式 */
.el-backtop {
  background-color: #409EFF;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.el-backtop:hover {
  background-color: #66b1ff;
  transform: translateY(-2px);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .main-content {
    padding: 10px;
  }
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>